from PySide6.QtWidgets import (QPushButton,  QSizePolicy)

from PySide6.QtCore import Qt, QEasingCurve, Property, QPropertyAnimation
from PySide6.QtGui import QPainter, QColor, QBrush

class SwitchWidget(QPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setCheckable(True)
        self._bg_color = "#c6c6c6"
        self._circle_x = 2

        self.setFixedSize(60, 30)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # 动画
        self._animation = QPropertyAnimation(self, b"circle_pos", self)
        self._animation.setDuration(150)
        self._animation.setEasingCurve(QEasingCurve.OutCubic)
        self.toggled.connect(self.animate)

    def paintEvent(self, event):
        """绘制固定尺寸的背景与圆点"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制区域（固定大小，不随布局变化）
        w, h = 60, 30
        x = (self.width() - w) // 2
        y = (self.height() - h) // 2

        # 背景
        painter.setBrush(QBrush(QColor(self._bg_color)))
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(x, y, w, h, h / 2, h / 2)

        # 白色圆点
        circle_d = h - 6  # 圆点略小一点
        painter.setBrush(QBrush(Qt.white))
        painter.drawEllipse(x + self._circle_x, y + 3, circle_d, circle_d)

        painter.end()

    def animate(self, checked):
        """开关动画 - 修正版"""
        w, h = 60, 30  # 固定尺寸
        margin = 3      # 左右边距
        circle_d = h - 6  # 圆点直径
        
        # 计算移动范围
        travel = w - circle_d - 2 * margin
        
        start = margin if checked else travel + margin
        end = travel + margin if checked else margin

        self._bg_color = "#4CAF50" if checked else "#c6c6c6"
        self._animation.stop()
        self._animation.setStartValue(start)
        self._animation.setEndValue(end)
        self._animation.start()


    def get_circle_pos(self):
        return self._circle_x

    def set_circle_pos(self, pos):
        self._circle_x = pos
        self.update()

    circle_pos = Property(int, get_circle_pos, set_circle_pos)
